package com.da.lon.wang.xlg.adapter;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.activity.ProductsActivity;
import com.da.lon.wang.xlg.bean.Goods;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.util.PreferenceUtils;
import com.da.lon.wang.xlg.util.Utils;
import com.da.lon.wang.xlg.util.ViewHolder;
import com.da.lon.wang.xlg.view.MyViewPager;
import com.da.lon.wang.xlg.view.TimerTextView;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.List;

public class GroupBuyAdapter extends BaseAdapter {

    private List<Goods> goods;
    private LayoutInflater inflater;
    private ImageLoader loader;
    private Activity context;

    public GroupBuyAdapter(List<Goods> good, Activity context) {
        // TODO Auto-generated constructor stub
        loader = ImageLoader.getInstance();
        this.context = context;
        inflater = LayoutInflater.from(context);
        this.goods = good;

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return goods != null ? goods.size() : 0;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return goods.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

        final Goods good = goods.get(position);

        final Holder holder;
        /* if(convertView==null){ */
        holder = new Holder();
        try {
            convertView = inflater.inflate(
                    R.layout.ouka_buyer_groupbuy_listviewitem, null);

            TimerTextView timerTextView = ViewHolder.get(convertView,
                    R.id.groupbuy_list_timer);
            TextView name = ViewHolder.get(convertView, R.id.name);
            ImageButton share = ViewHolder.get(convertView, R.id.share);
            TextView title = ViewHolder.get(convertView, R.id.title);
            TextView nowprice = ViewHolder.get(convertView, R.id.nowprice);
            TextView beforeprice = ViewHolder
                    .get(convertView, R.id.beforeprice);
            TextView gounum = ViewHolder.get(convertView, R.id.gounum);
            TextView opennum = ViewHolder.get(convertView, R.id.opennum);
            TextView gou = ViewHolder.get(convertView, R.id.gou);
            ProgressBar jingdu = ViewHolder.get(convertView, R.id.jingdu);
            MyViewPager pager = ViewHolder.get(convertView,
                    R.id.group_buy_viewpager);
            ViewGroup group = ViewHolder
                    .get(convertView, R.id.group_buy_dot_ll);

            share.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    try {
                        String pro_name = good.getName();
                        String uri = good.getUrl();
                        if (pro_name == null) {
                            pro_name = "";
                        }
                        if (uri == null) {
                            uri = "";
                        }
                        Utils.showShare(context, pro_name, null, uri, null);
                    } catch (Exception e) {
                        Toast.makeText(context, "参数有误", Toast.LENGTH_SHORT)
                                .show();
                    }
                }
            });

            holder.tips = new ImageView[good.getBigimage().length];
            for (int i = 0; i < holder.tips.length; i++) {
                ImageView imageView = new ImageView(context);
                imageView.setLayoutParams(new LayoutParams(20, 20));
                holder.tips[i] = imageView;
                if (i == 0) {
                    holder.tips[i]
                            .setBackgroundResource(R.drawable.page_indicator_unfocused);
                } else {
                    holder.tips[i]
                            .setBackgroundResource(R.drawable.page_indicator_focused);
                }

                group.addView(imageView);
            }
            convertView.setTag(holder);
            // }
            // holder=(Holder) convertView.getTag();

            name.setText(good.getName());
            title.setText(good.getSub_title());
            nowprice.setText(good.getPricespe() + "");
            beforeprice.setText("￥" + good.getPrice() + "");
            beforeprice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            opennum.setText("(" + good.getOpen_num() + "人团)");
            gounum.setText(good.getNow_num() + "人");

            jingdu.setMax(good.getOpen_num());
            jingdu.setProgress(good.getNow_num());

            int[] res = getTime(good.getEnd_time());

            timerTextView.setTimes(res);

            if (res[0] == 0 && res[1] == 0 && res[2] == 0) {
                timerTextView.stopRun();
            } else {
                timerTextView.beginRun();
            }

            // holder.miao.setText(res[0]);
            // holder.fen.setText(res[1]);
            // holder.shi.setText(res[2]);

            pager.setAdapter(new ImagePagerAdapter(context, good.getBigimage(),
                    good.getProduct_number()));
            pager.setOnPageChangeListener(new OnPageChangeListener() {

                @Override
                public void onPageSelected(int arg0) {
                    // TODO Auto-generated method stub
                    setImageBackground(holder, arg0);
                }

                @Override
                public void onPageScrolled(int arg0, float arg1, int arg2) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onPageScrollStateChanged(int arg0) {
                    // TODO Auto-generated method stub

                }
            });
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        return convertView;
    }

    private void setImageBackground(Holder holder, int selectItems) {
        try {
            for (int i = 0; i < holder.tips.length; i++) {
                if (i == selectItems) {
                    holder.tips[i]
                            .setBackgroundResource(R.drawable.page_indicator_unfocused);
                } else {
                    holder.tips[i]
                            .setBackgroundResource(R.drawable.page_indicator_focused);
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

    private int[] getTime(long tim) {

        long time = (tim - System.currentTimeMillis() / 1000);

        if ((int) (time) > 0) {
            int m = (int) (time % 60);

            int fe = (int) (time / 60) % 60;
            int shi = (int) (time / 3600);

            return new int[]{shi, fe, m};
        } else {

            int m = 0;
            int fe = 0;
            int shi = 0;

            return new int[]{shi, fe, m};
        }

    }

    public class Holder {

        ImageView[] tips;

    }

    private class ImagePagerAdapter extends PagerAdapter {

        private LayoutInflater inflater;
        private ImageView imageView;
        private String[] urls;
        private String url;

        ImagePagerAdapter(Activity context, String[] us, String url) {

            inflater = context.getLayoutInflater();
            this.urls = us;
            this.url = url;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager) container).removeView((View) object);
        }

        @Override
        public void finishUpdate(View container) {
        }

        @Override
        public int getCount() {
            return urls.length;
        }

        @Override
        public Object instantiateItem(ViewGroup view, int position) {
            View imageLayout = null;
            try {
                imageLayout = inflater.inflate(R.layout.item_pager_image, view,
                        false);

                imageView = (ImageView) imageLayout.findViewById(R.id.image);
                imageView.setScaleType(ScaleType.CENTER_INSIDE);

                imageView.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub

                        PreferenceUtils.getInstance().SetSettingString(
                                PreferencesConfig.PRODUCT_NUMBER, url);

                        Intent intent = new Intent(context,
                                ProductsActivity.class);

                        context.startActivity(intent);
                    }
                });
                MyApplication.loadImageByPicasso(context, urls[position], null, imageView, 0, 0, 0);
                ((ViewPager) view).addView(imageLayout, 0); // 将图片增加到ViewPager
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }

            return imageLayout;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view.equals(object);
        }

        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View container) {
        }
    }
}
